<?php
import('attachment.abstract');

class baseImg extends attachment_abstract
{
    // 如果是*，代表任意类型 $allow_exts
    // maxfilesize 以M为计算单位
    public $allow_exts = 'gif|jpg|jpeg|bmp|png', $maxfilesize = 10;

    protected $info;

    public $savePath;

    function __construct($dir = null, $allow_exts = null, $maxfilesize = null)
    {
        parent::__construct($dir);

        if (!$dir) {
            $dir = null;
        }

        $this->set($dir, $allow_exts, $maxfilesize);
    }

    function set($dir, $allow_exts = null, $maxfilesize = null)
    {
        if (!is_null($maxfilesize)) {
            $this->maxfilesize = $maxfilesize;
        }
        $this->maxfilesize = $this->maxfilesize * 1024;
        parent::set($dir, $allow_exts);
    }

    function execute($files, $selfUploadUrl = '', $isHttp = true)
    {
        if (!$this->_check($files)) {
            return false;
        }

        if (!$selfUploadUrl) {
            $selfUploadUrl = UPLOAD_URL;
        }

        $uploadFiles = [];

        if (!empty($files)) {
            if (is_array($files) && !empty($files)) {
                foreach ($files as $file) {
                    if ($file) {
                        if ($path = self::_baseImgValidate($file, $selfUploadUrl)) {
                            $uploadFiles[] = $path;
                        }
                    }
                }
            } else {
                if (is_string($files)) {
                    if ($path = self::_baseImgValidate($files, $selfUploadUrl)) {
                        $uploadFiles[] = $path;
                    }
                }
            }
        }
        if ($uploadFiles && $isHttp) {
            foreach ($uploadFiles as &$file) {
                $file = preg_replace('#(.*)upload/#i', '', $file);
            }
        }

        return $uploadFiles;
    }

    function error()
    {
        $ERROR = [
            1 => '上传的文件超过了选项限制的值',
            2 => '文件类型不支持',
            3 => '文件格式不符合',
            4 => '文件移动出错',
        ];
        return $ERROR[$this->errno];
    }

    private function _move()
    {
        if (!$this->filename) {
            $this->set_filename(null, $this->info[2]);
        }
        $path = $this->dir . $this->filename;

        if(!file_put_contents($path, base64_decode($this->info[3]))){
            $this->errno = 4;
            return false;
        }

        return $path;
    }

    private function _check($file)
    {
        if (!$this->_checkBaseIsValid($file)) {
            $this->errno = 2;
            return false;
        }

        if (!$this->_checkBaseMaxSize()) {
            $this->errno = 1;
            return false;
        }

        if (!$this->_checkBaseExt($this->info[2])) {
            $this->errno = 3;
            return false;
        }

        return true;
    }

    private function _checkBaseIsValid($file)
    {
        preg_match('/^(data:\s*image\/(\w+);base64,)(.*)/', $file, $this->info);

        return $this->info ? true : false;
    }

    private function _checkBaseMaxSize()
    {
        $length = strlen($this->info[3]);

        $length = number_format((($length - ($length/8) * 2)/1024), 2);

        return $this->maxfilesize > $length ? true : false;
    }

    private function _checkBaseExt($extension)
    {
        if (!in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png'], true)) {
            return false;
        }

        return true;
    }

    private function _baseImgValidate($thumb, $selfUploadUrl)
    {
        if(filter_var($thumb, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) {
            preg_match('#^'.preg_quote($selfUploadUrl).'#', $thumb, $myThumb);
            if ($myThumb) {
                $path = str_replace($selfUploadUrl, '', $thumb);
            } else {
                $path = $thumb;
            }
        } else {
            $path = self::_move();
        }

        return $path ?: false;
    }
}